<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/25
 * Time: 19:22
 */


function getShopifyDb(){
    static $db;
    if(!$db){
        $db = mysqli_connect(DB_HOSTNAME,DB_USERNAME, DB_PASSWORD, DB_DATABASE_SHOPIFY,DB_PORT);
    }
    if(!$db){
        die("db error");
    }
    return $db;
}

function getEachVapeDb(){
    static $db;
    if(!$db){
        $db = mysqli_connect(DB_HOSTNAME,DB_USERNAME, DB_PASSWORD, DB_DATABASE_EACHEVAPE,DB_PORT);
    }
    return $db;
}

function getApiUrl($path){
    $url =  sprintf("https://%s:%s@%s%s", API_KEY, API_PASSWORD, STORE,$path) ;
    return $url;
}

function addProducts($data)
{
    $db = getShopifyDb();

    $sql_p_if = "SELECT count(id) as cnt FROM product WHERE  id = '" . $data['id'] . "'";
    $rs_p_if = mysqli_query($db, $sql_p_if);
    $row_p_if = mysqli_fetch_assoc($rs_p_if);
    if ($row_p_if['cnt'] > 0) {

    } else {
        $sql_p = "INSERT INTO product(product_id, handle,created_at,updated_at) values  ";
        $sql_p .= "(";
        $sql_p .= "'" . $data['id'] . "',";
        $sql_p .= "'" . $data['handle'] . "',";
        $sql_p .= "'" . date('Y-m-d H:i:s',strtotime($data['created_at'])) . "',";
        $sql_p .= "'" . date('Y-m-d H:i:s',strtotime($data['updated_at'])) . "'";
        $sql_p .= ")";
        //echo $sql_p."<br/>";
        mysqli_query($db, $sql_p);
    }

    foreach($data['variants'] as $item) {

        //$sql_v_if = "SELECT * FROM product_variants WHERE  id = '" . $item['id'] . "' AND  product_id = '" . $data['id'] . "'";
        //$rs_v_if = mysqli_query($db, $sql_v_if);
        //$row_v_if = mysqli_fetch_assoc($rs_v_if);
        /*
        if ($row_v_if) {
            if($row_v_if['sku'] == '' &&  $item['sku'] != ''){
                $sql_v = "REPLACE INTO product_variants(variants_id,product_id, sku,inventory_quantity,inventory_item_id,requires_shipping,weight_unit,weight) values  ";
                $sql_v .= "(";
                $sql_v .= "'" . $item['id'] . "',";
                $sql_v .= "'" . $item['product_id'] . "',";
                $sql_v .= "'" . $item['sku'] . "',";
                $sql_v .= "'" . $item['inventory_quantity'] . "',";
                $sql_v .= "'" . $item['inventory_item_id'] . "',";
                $sql_v .= "'" . $item['requires_shipping'] . "',";
                $sql_v .= "'" . $item['weight_unit'] . "',";
                $sql_v .= "'" . $item['weight'] . "'";
                $sql_v .= ")";
                echo $sql_v."<br/>";
                mysqli_query($db, $sql_v);
            }
        } else {
        */
            $sql_v = "REPLACE INTO product_variants(variants_id,product_id, sku,inventory_quantity,inventory_item_id,requires_shipping,weight_unit,weight) values  ";
            $sql_v .= "(";
            $sql_v .= "'" . $item['id'] . "',";
            $sql_v .= "'" . $item['product_id'] . "',";
            $sql_v .= "'" . $item['sku'] . "',";
            $sql_v .= "'" . $item['inventory_quantity'] . "',";
            $sql_v .= "'" . $item['inventory_item_id'] . "',";
            $sql_v .= "'" . $item['requires_shipping'] . "',";
            $sql_v .= "'" . $item['weight_unit'] . "',";
            $sql_v .= "'" . $item['weight'] . "'";
            $sql_v .= ")";
            //echo $sql_v."<br/>";
            mysqli_query($db, $sql_v);
        //}
    }
}


function createShopifyOrder($order_id){
    $db = getEachVapeDb();
    $sql_order = "select * from oc_order where order_id = '" . $order_id . "'";
    $rs_order  = mysqli_query($db, $sql_order);
    $row_order = mysqli_fetch_assoc($rs_order);

    $sql_order_product = "SELECT * FROM oc_order_product where order_id  = '{$order_id}'";
    $rs_order_product  = mysqli_query($db, $sql_order_product);

    $shopify_products = [];
    $num = 0;
    while($row_order_product = mysqli_fetch_assoc($rs_order_product)){
        $num ++ ;
        $product_id = $row_order_product['product_id'];
        $model = $row_order_product["model"];
        $quantity = $row_order_product["quantity"];
        $handle = getProductHandle($product_id);

        if($handle){
            $variant_id = getShopifyVariantId($handle, $model);
            if($variant_id){
                $shopify_products[] = [
                    'variant_id' => $variant_id,
                    'quantity'   => $quantity,
                ];
            }
        }
    }

    if($num != count($shopify_products) ){
        return false;
    }
    $shipping_price = 0;
    $sql_total = "SELECT * FROM oc_order_total WHERE order_id = '" . $order_id . "' AND  code = 'shipping'";
    $rs_total  = mysqli_query($db,$sql_total);
    $row_total = mysqli_fetch_assoc($rs_total);
    if($row_total){
        $shipping_price =  $row_total['value'];
    }

    $shopify_order = [];
    $shopify_order['order'] = [
        'line_items'       => $shopify_products,
        'billing_address'  => BILLING_ADDRESS,
        'shipping_address' => [
            "first_name"   => $row_order["shipping_firstname"],
            "last_name"    => $row_order["shipping_lastname"],
            "address1"     => $row_order["shipping_address_1"],
            "phone"        => $row_order['telephone'],
            "city"         => $row_order["shipping_city"],
            "province"     => $row_order["shipping_zone"],
            "country"      => $row_order["shipping_country"],
            "zip"          => $row_order["shipping_postcode"],
        ],
        "customer"         => [
            'id'   =>  SHOPIFY_CUSTOMER_ID,
        ],
        'financial_status'    => 'paid',
        'fulfillment_status'  => 'fulfilled',
        'inventory_behaviour' => 'decrement_obeying_policy',
        'shipping_lines'      => [
            [
                'code'  => $row_order['shipping_method'],
                'price' => $shipping_price,
                'title' => $row_order['shipping_method'],

            ],
            //"carrier_identifier"               => "third_party_carrier_identifier",
            //"requested_fulfillment_service_id" =>  "third_party_fulfillment_service_id",
        ],

    ];
    return $shopify_order;

}

function getProductHandle($product_id){
    $db  = getEachVapeDb();
    $sql = "SELECT * FROM oc_seo_url where  query ='product_id={$product_id}' AND language_id = 1 AND  store_id = 0 ";

    $rs  = mysqli_query($db, $sql);
    $row = mysqli_fetch_assoc($rs);
    if($row){
        return $row['keyword'];
    }
    return false;
}


/**
 * @param $handle
 * @param $model
 * @return bool
 */
function getShopifyVariantId($handle, $model){
    $db = getShopifyDb();
    $sql_product = "SELECT * FROM product WHERE handle = '" .  mysqli_escape_string($db, $handle). "'";
    $rs_product  = mysqli_query($db, $sql_product);
    $row_product = mysqli_fetch_assoc($rs_product);

    if($row_product){
        $product_id = $row_product['product_id'];
        $sql_product_variants = "SELECT * FROM product_variants WHERE product_id = '" . $product_id . "' AND  sku = '" . $model . "'";

        $rs_product_variants  = mysqli_query($db, $sql_product_variants);
        $row_product_variants = mysqli_fetch_assoc($rs_product_variants);

        if($row_product_variants){
            $product_variants_id  = $row_product_variants['variants_id'];
            return $product_variants_id;
        }

    }
    return false;
}

/**
 * 提交post json数据
 * @param $url
 * @param $data
 * @return bool|mixed
 */
function postJSON($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($data))
    );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    $errorno = curl_errno($ch);
    curl_close($ch);
    if ($errorno) {
       return false;
    }
    return $res;
}

/**
 * 添加订单同步接口历史记录
 * @param $order_id
 * @param $url
 * @param $result
 * @param $status
 */
function addOrderSyncHistory($order_id, $url, $result, $status){
    $db = getShopifyDb();
    $sql = "INSERT INTO order_sync_history(order_id,url,result,status,created_at) value (";
    $sql .= "'" . $order_id .   "',";
    $sql .= "'" . mysqli_escape_string($db, $url) .   "',";
    $sql .= "'" . mysqli_escape_string($db, $result) .   "',";
    $sql .= "'" . $status .   "',";
    $sql .= "now())";
    echo $sql;
    mysqli_query($db, $sql);
}

/**
 * 修改同步订单记录
 * @param $order_id
 * @param $shopify_order_id
 * @param $sync_status
 */
function updateOrderSync($order_id,$shopify_order_id, $sync_status ){
    $db = getShopifyDb();
    $sql_u  = "UPDATE order_sync SET sync_status = '" . $sync_status . "',  shopify_order_id = '" . $shopify_order_id . "', updated_at = now() WHERE order_id = '" . $order_id . "' ";
    mysqli_query($db, $sql_u);
}

/**
 * 添加同步订单记录
 * @param $order_id
 * @param $shopify_order_id
 * @param $sync_status
 */
function addOrderSync($order_id,$shopify_order_id, $sync_status ){
    $db = getShopifyDb();
    $sql_in  = "REPLACE INTO order_sync(order_id,sync_status,shopify_order_id,created_at,updated_at) value (";
    $sql_in .= "'" . $order_id . "',";
    $sql_in .= "'" . $sync_status . "',";
    $sql_in .= "'" . $shopify_order_id . "',";
    $sql_in .= "now(),";
    $sql_in .= "now())";
    mysqli_query($db, $sql_in);
}

function shopifyOrderSync($order_id){
    $shopify_order = createShopifyOrder($order_id);
    var_dump($shopify_order);
    $url = getApiUrl("/admin/orders.json");
    $shopify_order_json = postJSON($url, json_encode($shopify_order));
    $shopfiy_order_data = json_decode($shopify_order_json, true);
    $shopify_order_id = 0;
    $shopify_order_sync_status = 0;
    if(isset($shopfiy_order_data['order'])){
        $shopify_order_id = $shopfiy_order_data['order']['id'];
        $shopify_order_sync_status = 3;
    }else{

    }
    addOrderSync($order_id,$shopify_order_id,$shopify_order_sync_status);
    addOrderSyncHistory($order_id, $url,$shopify_order_json,$shopify_order_id > 0 ? 1:0 );
}